import {IUserModelType} from "../modelType/type";

import {Schema, model} from "mongoose";

const bcrypt = require("bcryptjs");

const userSchema = new Schema({
  account: {type: String, required: true, unique: true, index: true},
  password: {
    type: String, required: true,
    set(val: any) {
      return bcrypt.hashSync(val, 10);
    }
  },
  username: {type: String},
  createTime: {type: Number, default: Date.now()},
  phone: {type: String},
  email: {type: String},
  userRole: {type: [String]},
  gender: {type: String},
  description: {type: String},
  status: {type: Boolean}
});

const userModel = model("Users", userSchema);


const createSuperAccount = async (): Promise<boolean> => {
  const user = await userModel.findOne({account: "admin"}) as IUserModelType | null;
  if (!user) {
    const newUser = await userModel.create({
      account: "admin",
      password: "admin",
      userRole: ["admin"],
      username: "admin"
    });
    return !!newUser;
  }
  return true;
};

export {
  userModel,
  createSuperAccount
};